<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Support\Facades\Log;
use App\Common\Enums\Code;
use App\Common\Tools\DingTalk;

class BaseException extends Exception
{
    /**
     * 自定义异常数据
     *
     * @var mixed
     */
    protected $customData;

    /**
     * 构造
     *
     * @param integer $code
     * @param string $message
     * @param mixed $customData
     */
    public function __construct(int $code = 0, string $message = "", $customData = [])
    {
        parent::__construct($message, $code);
        $this->customData = $customData;
    }

    /**
     * 可以把保存信息写入日志
     */
    public function report()
    {
        // 记录日志，方便排查问题
        $code = $this->getCode();
        if (in_array($code, [Code::DB_EXCEPTION])) {
            Log::warning($this->getMessage(), ['data' => $this->customData]);

            // 发送钉钉预警
            if ($code != Code::ROBOT_SEND_MSG_FAIL) { // 此code就是发送钉钉失败的code
                // 发送钉钉提醒
                $env = '';
                if (!is_online()) {
                    $env = '【测试环境】';
                }
                $title = '用户中心运行异常，请关注';
                $jsonData = '';
                if (is_array($this->customData)) {
                    $jsonData = json_encode($this->customData);
                }
                $content = <<<MD
### {$env}代码运行异常

- 错误信息：{$this->getMessage()}
- 错误编号：{$this->code}
- 错误位置：{$this->getFile()} : {$this->getLine()}
- 错误数据：{$jsonData}
MD;
;
                DingTalk::getInstance()->to()->markdown($title, $content);
            }
        }

    }

    /**
     * 响应 json
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function render()
    {
        $responeData = [
            'code'    => $this->code, 
            'message' => $this->message, 
            'data'    => $this->customData
        ];
        if (!is_online()) {
            $responeData['file'] = sprintf('%s:%s', $this->getFile(), $this->getLine());
        }
        return response()->json($responeData);
    }
}
